package com.atguigu.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV2;
import com.atguigu.realtime.bean.OrderDetail;
import com.atguigu.realtime.bean.OrderInfo;
import com.atguigu.realtime.bean.OrderWide;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.DimUtil;
import com.atguigu.realtime.util.JdbcUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

import java.sql.Connection;
import java.time.Duration;
import java.util.Map;

import static com.atguigu.realtime.common.Constant.TOPIC_DWD_ORDER_DETAIL;
import static com.atguigu.realtime.common.Constant.TOPIC_DWD_ORDER_INFO;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/2/12 14:02
 */
public class DwmOrderWideApp extends BaseAppV2 {
    public static void main(String[] args) {
        new DwmOrderWideApp().init(
            3003,
            1,
            "DwmOrderWideApp",
            "DwmOrderWideApp",
            TOPIC_DWD_ORDER_INFO, TOPIC_DWD_ORDER_DETAIL
        );
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       Map<String, DataStreamSource<String>> topicStreamMap) {
        
        // 1. 实时表与事实表的join: 双流join   a:window join  b:interval join
        SingleOutputStreamOperator<OrderWide> orderWideStreamWithoutDim = factJoin(topicStreamMap);
        // 2. 事实表与维度表join: 手动join, 根据各个维度id, 通过jdbc去查询维度表, 得到堆一块那个的维度数据
        SingleOutputStreamOperator<OrderWide> orderWideStreamWithDim = factDim(orderWideStreamWithoutDim);
        orderWideStreamWithDim.print();
        
        // 2.1 旁路缓存优化
        // 2.2 异步优化
        
        // 3. 把join后的宽表写入到Kafka中(dws_order_wide)
        
    }
    
    private SingleOutputStreamOperator<OrderWide> factDim(SingleOutputStreamOperator<OrderWide> orderWideStreamWithoutDim) {
        /*
        如何join维度信息:
            OrderWide user_id, 通过这个id, 去Phoenix中查找这个id对应的用户信息
                        sku_id ...
                        spu_id ...
         */
        return orderWideStreamWithoutDim.map(new RichMapFunction<OrderWide, OrderWide>() {
            
            private Connection conn;
            
            @Override
            public void open(Configuration parameters) throws Exception {
                conn = JdbcUtil.getConnection(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL);
            }
            
            @Override
            public void close() throws Exception {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            
            @Override
            public OrderWide map(OrderWide orderWide) throws Exception {
                
                // 1. userInfo
                JSONObject userInfo = DimUtil.readDimFromPhoenix(conn, "dim_user_info", orderWide.getUser_id());
                orderWide.setUser_gender(userInfo.getString("GENDER"));
                orderWide.calculateUserAge(userInfo.getString("BIRTHDAY"));
                // 2. base_province
                JSONObject baseProvince = DimUtil.readDimFromPhoenix(conn, "dim_base_province", orderWide.getProvince_id());
                orderWide.setProvince_name(baseProvince.getString("NAME"));
                orderWide.setProvince_3166_2_code(baseProvince.getString("ISO_3166_2"));
                orderWide.setProvince_area_code(baseProvince.getString("AREA_CODE"));
                orderWide.setProvince_iso_code(baseProvince.getString("ISO_CODE"));
                
                // 3. sku_info  一定要先查sku_info, 这样才能查到spu_id, 然后再根据spu_id去spu_info中查spu_name
                JSONObject skuInfo = DimUtil.readDimFromPhoenix(conn, "dim_sku_info", orderWide.getSku_id());
                orderWide.setSku_name(skuInfo.getString("SKU_NAME"));
                orderWide.setOrder_price(skuInfo.getBigDecimal("PRICE"));
                
                
                orderWide.setSpu_id(skuInfo.getLong("SPU_ID"));
                orderWide.setTm_id(skuInfo.getLong("TM_ID"));
                orderWide.setCategory3_id(skuInfo.getLong("CATEGORY3_ID"));
                
                // 4. spu_info
                JSONObject spuInfo = DimUtil.readDimFromPhoenix(conn, "dim_spu_info", orderWide.getSpu_id());
                orderWide.setSpu_name(spuInfo.getString("SPU_NAME"));
                
                // 5. base_trademark
                JSONObject baseTrademark = DimUtil.readDimFromPhoenix(conn, "dim_base_trademark", orderWide.getTm_id());
                orderWide.setTm_name(baseTrademark.getString("TM_NAME"));
                
                // 6. c3
                JSONObject baseCategory3 = DimUtil.readDimFromPhoenix(conn, "dim_base_category3", orderWide.getCategory3_id());
                orderWide.setCategory3_name(baseCategory3.getString("NAME"));
                
                return orderWide;
            }
        });
        
    }
    
    private SingleOutputStreamOperator<OrderWide> factJoin(Map<String, DataStreamSource<String>> topicStreamMap) {
        KeyedStream<OrderInfo, Long> orderInfoStream = topicStreamMap
            .get(TOPIC_DWD_ORDER_INFO)
            .map(info -> JSON.parseObject(info, OrderInfo.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderInfo>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((info, ts) -> info.getCreate_ts())
            )
            .keyBy(OrderInfo::getId);
        
        KeyedStream<OrderDetail, Long> orderDetailStream = topicStreamMap
            .get(TOPIC_DWD_ORDER_DETAIL)
            .map(info -> JSON.parseObject(info, OrderDetail.class))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderDetail>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((detail, ts) -> detail.getCreate_ts())
            )
            .keyBy(OrderDetail::getOrder_id);
        
        return orderInfoStream
            .intervalJoin(orderDetailStream)
            .between(Time.seconds(-5), Time.seconds(5))
            .process(new ProcessJoinFunction<OrderInfo, OrderDetail, OrderWide>() {
                @Override
                public void processElement(OrderInfo orderInfo,
                                           OrderDetail orderDetail,
                                           Context ctx,
                                           Collector<OrderWide> out) throws Exception {
                    out.collect(new OrderWide(orderInfo, orderDetail));
                }
            });
        
    }
}
